1. 使用UIView.layer.cornerRadius
进行圆角设置
1 2
| view.layer.cornerRadius = 20; view.layer. masksToBounds = YES;
|
此处view.layer. masksToBounds = YES;
会触发离屏渲染,如果在UITableViewCell和UICollectionViewCell中使用,严重的会掉帧、不流畅
2.使用贝塞尔曲线画圆角及指定位置圆角
1 2 3 4 5 6 7
| CGFloat radius = 20; UIRectCorner corner = UIRectCornerAllCorners; UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = view.bounds; maskLayer.path = path.CGPath; view.layer.mask = maskLayer;
|
UIRectCorner 的定义如下
1 2 3 4 5 6 7
| typedef NS_OPTIONS(NSUInteger, UIRectCorner) { UIRectCornerTopLeft = 1 << 0, UIRectCornerTopRight = 1 << 1, UIRectCornerBottomLeft = 1 << 2, UIRectCornerBottomRight = 1 << 3, UIRectCornerAllCorners = ~0UL };
|
UIRectCorner 可以使用位运算进行圆角设置,如:
1
| UIRectCorner corner = UIRectCornerTopRight | UIRectCornerBottomRight;
|
圆角加边框
1 2 3 4 5 6 7 8 9 10 11
| CGFloat radius = 20; UIRectCorner corner = UIRectCornerAllCorners; UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = view.bounds; maskLayer.path = path.CGPath;
maskLayer.strokeColor = [UIColor redColor].CGColor; maskLayer.fillColor = [UIColor yellowColor].CGColor; [view.layer addSublayer:maskLayer];
|
3.iOS11 新特性——改善view圆角
1 2 3 4
| if (@available(iOS 11.0, *)) { view.layer.cornerRadius = radius; view.layer.maskedCorners = kCALayerMinXMinYCorner; }
|
CACornerMask的定义如下:
1 2 3 4 5 6 7 8
| typedef NS_OPTIONS (NSUInteger, CACornerMask) { kCALayerMinXMinYCorner = 1U << 0, kCALayerMaxXMinYCorner = 1U << 1, 右上 kCALayerMinXMaxYCorner = 1U << 2, kCALayerMaxXMaxYCorner = 1U << 3, }; CACornerMask 如同上面的UIRectCorner 可以使用位运算进行圆角设置
|
4.对UIView进行自定义圆角分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @interface UIView (ACSLayer)
- (void)acs_radiusWithRadius:(CGFloat)radius corner:(UIRectCorner)corner { if (@available(iOS 11.0, *)) { self.layer.cornerRadius = radius; self.layer.maskedCorners = (CACornerMask)corner; } else { UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = self.bounds; maskLayer.path = path.CGPath; self.layer.mask = maskLayer; } } @end
|
此方法在iOS 11 中使用iOS 11中的maskedCorners进行圆角设置,如是iOS 11 以下则使用贝塞尔曲线画圆角。